<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1600">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="巡查单号" prop="no">
            <el-input disabled v-model="formData.no" placeholder="保存时自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检验时间" prop="checkTime">
            <el-date-picker
              v-model="formData.checkTime"
              type="date"
              value-format="x"
              placeholder="选择检验时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="班次" prop="shift">
            <el-select v-model="formData.shift" placeholder="请输入班次" clearable >
              <el-option label="白班" value="白班"/>
              <el-option label="晚班" value="晚班"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="机器" prop="machine">
            <el-input v-model="formData.machine" placeholder="请输入机器" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="模具" prop="mould">
            <el-input v-model="formData.mould" placeholder="请输入模具" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品" prop="product">
            <el-input v-model="formData.product" placeholder="请输入产品" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="订单编号" prop="orderNo">
            <el-input v-model="formData.orderNo" placeholder="请输入订单编号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单数量" prop="orderCount">
            <el-input v-model="formData.orderCount" placeholder="请输入订单数量" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="材质" prop="texture">
            <el-input v-model="formData.texture" placeholder="请输入材质" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="颜色" prop="color">
            <el-input v-model="formData.color" placeholder="请输入颜色" />
          </el-form-item>
        </el-col>

      </el-row>

      <!-- 检查指引和注意事项 -->
      <el-row :gutter="20" style="margin-bottom: 20px">
        <el-col :span="24">
          <el-collapse v-model="activeNames" style="border: 1px solid #409eff; border-radius: 4px">
            <el-collapse-item name="1">
              <template #title>
                <div style="color: #409eff; font-weight: bold; font-size: 14px">
                  <el-icon style="margin-right: 5px"><InfoFilled /></el-icon>
                  检查指引与注意事项（请仔细阅读）
                </div>
              </template>

              <!-- 检查指引 -->
              <div style="margin-bottom: 15px">
                <h4 style="color: #303133; margin: 10px 0">一、检查指引</h4>
                <div style="padding-left: 20px; line-height: 1.8">
                  <p><strong>1. 目视检查：</strong>目视30CM检查外观是否存在不良，需参考模版程度。</p>
                  <p><strong>2. 部位核对：</strong>目视30CM与样品核对各扣位、柱位、顶针位、斜顶位等部位，检查是否出现以下情况：</p>
                  <ul style="padding-left: 20px">
                    <li>扣位变形</li>
                    <li>柱斜</li>
                    <li>柱孔偏</li>
                    <li>顶针位与斜顶位深浅不一致</li>
                  </ul>
                  <p><strong>3. 尺寸检验：</strong>尺寸按图纸或样品量测，<span style="color: #f56c6c; font-weight: bold">超出公差判定为NG</span>。</p>
                </div>
              </div>

              <!-- 巡检频率 -->
              <div style="margin-bottom: 15px; background: #f0f9ff; padding: 10px; border-radius: 4px">
                <h4 style="color: #303133; margin: 10px 0">二、巡检频率</h4>
                <div style="padding-left: 20px; line-height: 1.8">
                  <p><strong>• 外观：</strong><span style="color: #409eff; font-weight: bold">3pcs/1H</span> （每小时抽检3件）</p>
                  <p><strong>• 尺寸：</strong><span style="color: #409eff; font-weight: bold">1pcs/1H</span> （每小时抽检1件）</p>
                  <p><strong>• 功能：</strong><span style="color: #409eff; font-weight: bold">1pcs/1H</span> （每小时抽检1件）</p>
                  <p><strong>• 单重：</strong><span style="color: #409eff; font-weight: bold">1pcs/4H</span> （每4小时抽检1件）</p>
                </div>
              </div>

              <!-- 注意事项 -->
              <div style="background: #fff3e0; padding: 10px; border-radius: 4px; border-left: 4px solid #ff9800">
                <h4 style="color: #303133; margin: 10px 0">三、注意事项</h4>
                <div style="padding-left: 20px; line-height: 1.8">
                  <p><strong>1. 记录要求：</strong>IPQC选择缺陷项将代号写入被检查内容，并记录不良数。</p>
                  <p><strong>2. 异常处理：</strong><span style="color: #f56c6c; font-weight: bold">有生产异常时，需马上停止生产并填写《制程异常报告》</span>。</p>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-col>
      </el-row>

      <el-form-item label="检验数据" prop="checkData">
        <el-table :data="checkData" border style="width: 100%" size="small">
          <el-table-column label="序号" type="index" width="60" align="center" />
          <el-table-column label="巡检时段" align="center" width="150">
            <template #default="{ row }">
              <el-input v-model="row.timeSlot" placeholder="请输入巡检时段" style="width: 100%"/>
            </template>
          </el-table-column>
          <el-table-column label="抽检数量" align="center" width="100">
            <template #default="{ row }">
              <el-input-number
                v-model="row.sampleCount"
                :min="0"
                :controls="false"
                style="width: 100%"
                @change="calculateDefectRate(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="单重" align="center" width="120">
            <template #default="{ row }">
              <el-input v-model="row.weight" placeholder="单重(g)" />
            </template>
          </el-table-column>
          <el-table-column label="外观" align="center" min-width="120">
            <template #default="{ row }">
              <el-select v-model="row.appearance" placeholder="请选择">
                <el-option label="合格" value="合格" />
                <el-option label="不合格" value="不合格" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="功能" align="center" min-width="120">
            <template #default="{ row }">
              <el-select v-model="row.function" placeholder="请选择">
                <el-option label="正常" value="正常" />
                <el-option label="异常" value="异常" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="标准尺寸(带公差)" align="center" min-width="180">
            <template #default="{ row }">
              <el-input
                type="textarea"
                v-model="row.standardSize"
                placeholder="例：100±0.5mm"
                :autosize="{ minRows: 1, maxRows: 3 }"
              />
            </template>
          </el-table-column>
          <el-table-column label="不良数量" align="center" width="100">
            <template #default="{ row }">
              <el-input-number
                v-model="row.defectCount"
                :min="0"
                :max="row.sampleCount"
                :controls="false"
                style="width: 100%"
                @change="calculateDefectRate(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="不良率" align="center" width="80">
            <template #default="{ row }">
              {{ row.defectRate || '0%' }}
            </template>
          </el-table-column>
          <el-table-column label="异常处理" align="center" min-width="150">
            <template #default="{ row }">
              <el-input
                type="textarea"
                v-model="row.exceptionHandle"
                placeholder="异常处理措施"
                :autosize="{ minRows: 1, maxRows: 3 }"
              />
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" min-width="150">
            <template #default="{ row }">
              <el-input
                type="textarea"
                v-model="row.remark"
                placeholder="备注"
                :autosize="{ minRows: 1, maxRows: 3 }"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80" fixed="right">
            <template #default="{ $index }">
              <el-button link type="danger" @click="removeRow($index)" :icon="Delete">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          plain
          @click="addRow"
          style="margin-top: 10px; width: 100%"
          :icon="Plus"
        >
          添加巡检记录
        </el-button>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" :rows="2" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="附件 URL" prop="fileUrl">
               <upload-file v-model="formData.fileUrl" :isShowTip="false"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { CheckPatrolApi, CheckPatrol } from '@/api/erp/check/patrol'
import { Delete, Plus, InfoFilled } from '@element-plus/icons-vue'

/** ERP 巡查检验 表单 */
defineOptions({ name: 'CheckPatrolForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const activeNames = ref(['1']) // 折叠面板默认展开检查指引
const formData = ref({
  id: undefined,
  no: undefined,
  checkTime: undefined,
  checkData: undefined,
  shift: undefined,
  machine: undefined,
  mould: undefined,
  product: undefined,
  orderId: undefined,
  orderNo: undefined,
  orderCount: undefined,
  texture: undefined,
  color: undefined,
  status: undefined,
  remark: undefined,
  fileUrl: undefined
})
const formRules = reactive({
  checkTime: [{ required: true, message: '检验时间不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

// 检验数据表格定义
interface CheckDataItem {
  timeSlot: string// 巡检时段(时间范围数组)
  sampleCount: number // 抽检数量
  weight: string // 单重
  appearance: string // 外观
  function: string // 功能
  standardSize: string // 标准尺寸(带公差)
  defectCount: number // 不良数量
  defectRate: string // 不良率(自动计算)
  exceptionHandle: string // 异常处理
  remark: string // 备注
}

const checkData = ref<CheckDataItem[]>([])

/** 计算不良率 */
const calculateDefectRate = (row: CheckDataItem) => {
  if (row.sampleCount > 0 && row.defectCount >= 0) {
    const rate = ((row.defectCount / row.sampleCount) * 100).toFixed(2)
    row.defectRate = rate + '%'
  } else {
    row.defectRate = '0%'
  }
}

/** 添加巡检记录行 */
const addRow = () => {
  checkData.value.push({
    timeSlot: '',
    sampleCount: 0,
    weight: '',
    appearance: '',
    function: '',
    standardSize: '',
    defectCount: 0,
    defectRate: '0%',
    exceptionHandle: '',
    remark: ''
  })
}

/** 删除巡检记录行 */
const removeRow = (index: number) => {
  checkData.value.splice(index, 1)
}

/** 初始化检验数据模板 */
const initCheckData = () => {
  return [
    {
      timeSlot: '08:00-10:00',
      sampleCount: 0,
      weight: '',
      appearance: '',
      function: '',
      standardSize: '',
      defectCount: 0,
      defectRate: '0%',
      exceptionHandle: '',
      remark: ''
    },
    {
      timeSlot: '10:00-12:00',
      sampleCount: 0,
      weight: '',
      appearance: '',
      function: '',
      standardSize: '',
      defectCount: 0,
      defectRate: '0%',
      exceptionHandle: '',
      remark: ''
    },
    {
      timeSlot: '12:00-14:00',
      sampleCount: 0,
      weight: '',
      appearance: '',
      function: '',
      standardSize: '',
      defectCount: 0,
      defectRate: '0%',
      exceptionHandle: '',
      remark: ''
    },
    {
      timeSlot: '14:00-16:00',
      sampleCount: 0,
      weight: '',
      appearance: '',
      function: '',
      standardSize: '',
      defectCount: 0,
      defectRate: '0%',
      exceptionHandle: '',
      remark: ''
    },
    {
      timeSlot: '16:00-18:00',
      sampleCount: 0,
      weight: '',
      appearance: '',
      function: '',
      standardSize: '',
      defectCount: 0,
      defectRate: '0%',
      exceptionHandle: '',
      remark: ''
    },
    {
      timeSlot: '18:00-20:00',
      sampleCount: 0,
      weight: '',
      appearance: '',
      function: '',
      standardSize: '',
      defectCount: 0,
      defectRate: '0%',
      exceptionHandle: '',
      remark: ''
    }
  ]
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CheckPatrolApi.getCheckPatrol(id)

      // 解析 JSON 检验数据
      if (formData.value.checkData) {
        try {
          checkData.value = JSON.parse(formData.value.checkData as string)
        } catch (e) {
          console.error('检验数据解析失败:', e)
          checkData.value = initCheckData()
        }
      } else {
        // 修改时如果没有数据，初始化默认数据
        checkData.value = initCheckData()
      }
    } finally {
      formLoading.value = false
    }
  } else {
    // 新增时，初始化默认巡检时段
    checkData.value = initCheckData()
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CheckPatrol
    // 将检验数据表格转换为 JSON 字符串
    data.checkData = JSON.stringify(checkData.value)

    if (formType.value === 'create') {
      await CheckPatrolApi.createCheckPatrol(data)
      message.success(t('common.createSuccess'))
    } else {
      await CheckPatrolApi.updateCheckPatrol(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    no: undefined,
    checkTime: undefined,
    checkData: undefined,
    shift: undefined,
    machine: undefined,
    mould: undefined,
    product: undefined,
    orderId: undefined,
    orderNo: undefined,
    orderCount: undefined,
    texture: undefined,
    color: undefined,
    status: undefined,
    remark: undefined,
    fileUrl: undefined
  }
  // 重置检验数据表格（不清空，保持默认模板）
  checkData.value = []
  formRef.value?.resetFields()
}
</script>
